﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Common.Forms
{
    public abstract partial class Validating : Form
    {
        int time = -1;
        string progression = string.Empty;
        int timer_counter = 0;
        int delay = 2000;

        public Validating()
        {
            InitializeComponent();

            this.Text = Resources.CommonResources.Validating + progression;
        }

        public void UpdateProgress(String step, int currentStep, int totalStep)
        {
            if (prgStatus.InvokeRequired)
            {
                prgStatus.Invoke(new ProgressCallback(UpdateProgress), step, currentStep, totalStep);
                return;
            }

            lblStatus.Text = step;
            prgStatus.Maximum = totalStep;
            prgStatus.Value = currentStep;
        }

        public virtual void TestSuccess(int currentStep) { }
        public virtual void TestFail(int currentStep) { }

        private System.Threading.Thread t = null;

        protected virtual void Validating_Shown(object sender, EventArgs e)
        {
            System.Threading.ThreadStart ts = new System.Threading.ThreadStart(StartTest);
            t = new System.Threading.Thread(ts);

            t.Start();
        }

        protected abstract void StartTest();

        private void timerClosing_Tick(object sender, EventArgs e)
        {
            if (timer_counter == 0 && time < 0)
            {
                progression += ".";

                if (progression.Length > 3)
                    progression = string.Empty;

                this.Text = Resources.CommonResources.Validating + progression;
            }

            timer_counter = (timer_counter + 1) % 5;

            if (t != null && !t.IsAlive)
            {
                if (time == -1)
                {
                    time = Environment.TickCount;
                }
                else if (Environment.TickCount - time > delay + timerClosing.Interval)
                {
                    this.Close();
                }
                else
                {
                    this.Text = string.Format("{0} - {1} s", Resources.CommonResources.Failed, string.Format(Resources.CommonResources.Closing, delay / 1000 - (Environment.TickCount - time) / 1000));
                }
            }
        }
    }
}
